﻿
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Sykj.Components;
using Sykj.Infrastructure;
using Sykj.IServices;
using Sykj.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sykj.Web.Api.v1
{
    /// <summary>
    /// 消息管理
    /// </summary>
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public class MessageController : ApiController
    {
        #region 全局变量
        ISiteMessage _siteMessage;
        IUsers _users;
        IUserMember _userMember;
        #endregion

        #region 构造方法
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="siteMessage"></param>
        /// <param name="users"></param>
        /// <param name="userMember"></param>
        public MessageController(ISiteMessage siteMessage, IUsers users, IUserMember userMember)
        {
            _siteMessage = siteMessage;
            _users = users;
            _userMember = userMember;
        }
        #endregion

        #region 消息分类
        /// <summary>
        /// 消息分类  lh
        /// </summary>
        /// <returns></returns>
        [HttpGet("messagetype")]
        public ApiResult MessageType()
        {
            var userModel = _users.GetModel(c => c.UserId == UserId);
            if (userModel == null)
            {
                return Failed("用户信息错误！");
            }
            //系统消息
            string subSystem = string.Empty;
            bool readSystem = true;

            //订单消息
            string subOrder = string.Empty;
            bool readOrder = true;

            //通知消息
            string subNotice = string.Empty;
            bool readNotice = true;

            //查询出分类下未读消息的数量
            var systemCount = _siteMessage.GetRecordCount(" MsgType=@0 AND ReceiverID=@1 AND ReceiverIsRead=@2 ", "System", userModel.UserId, false);
            var orderCount = _siteMessage.GetRecordCount(" MsgType=@0 AND ReceiverID=@1 AND ReceiverIsRead=@2", "Order", userModel.UserId, false);
            var noticeCount = _siteMessage.GetRecordCount(" MsgType=@0 AND ReceiverID=@1 AND ReceiverIsRead=@2", "Notice", userModel.UserId, false);

            //系统消息是否已读
            if (systemCount > 0)
            {
                readSystem = false;
            }

            //订单消息是否已读
            if (orderCount > 0)
            {
                readOrder = false;
            }

            //通知消息是否已读
            if (noticeCount > 0)
            {
                readNotice = false;
            }

            //查询出分类下最近的一条消息的内容
            var systemList = _siteMessage.GetList(1, " MsgType=@0 AND ReceiverID=@1 ", " SendTime DESC ", "System", userModel.UserId).ToList();
            var orderList = _siteMessage.GetList(1, " MsgType=@0 AND ReceiverID=@1 ", " SendTime DESC ", "Order", userModel.UserId).ToList();
            var noticeList = _siteMessage.GetList(1, " MsgType=@0 AND ReceiverID=@1 ", " SendTime DESC ", "Notice", userModel.UserId).ToList();

            if (systemList.Count > 0)
            {
                subSystem = systemList[0].Content;
            }

            if (orderList.Count > 0)
            {
                subOrder = orderList[0].Content;
            }

            if (noticeList.Count > 0)
            {
                subNotice = noticeList[0].Content;
            }
            var list = new List<object>();
            list.Add(new { title = "系统消息", img = BaseConfig.ImagesDoMain + "/upload/notice/icon_info_discount.png", subTitle = subSystem, time = DateTime.Now.ToShortDateString(), isRead = readSystem, msgType = "System" });
            list.Add(new { title = "订单消息", img = BaseConfig.ImagesDoMain + "/upload/notice/icon_info_order.png", subTitle = subOrder, time = DateTime.Now.ToShortDateString(), isRead = readOrder, msgType = "Order" });
            list.Add(new { title = "通知消息", img = BaseConfig.ImagesDoMain + "/upload/notice/icon_info_notice.png", subTitle = subNotice, time = DateTime.Now.ToShortDateString(), isRead = readNotice, msgType = "Notice" });
            return DataResult(list);
        }
        #endregion

        #region 用户消息列表
        /// <summary>
        /// 用户消息列表 lh
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="msgType">0:系统消息  1:订单消息  2:通知消息</param>
        /// <returns></returns>
        [HttpGet("messagelist")]
        public ApiResult MessageList(int pageIndex, int pageSize, string msgType)
        {
            var userModel = _users.GetModel(c => c.UserId == UserId);
            if (userModel == null)
            {
                return Failed("用户信息错误！");
            }
            var list = _siteMessage.GetPagedList(pageIndex, pageSize, " ReceiverID=@0 AND MsgType=@1", " SendTime DESC ", userModel.UserId, msgType.ToString());
            int count = _siteMessage.GetRecordCount(" ReceiverID=@0 AND MsgType=@1", userModel.UserId, msgType.ToString());
            _siteMessage.UpdateIsRead(msgType.ToString(), userModel.UserId);
            return ListResult(list, count);
        }
        #endregion

        #region 消息全部读取
        /// <summary>
        /// 消息全部读取 lh
        /// </summary>
        /// <param name="msgType">0:系统消息  1:订单消息  2:通知消息</param>
        /// <returns></returns>
        [HttpGet("messageread")]
        public ApiResult MessageRead(string msgType)
        {
            var userModel = _users.GetModel(c => c.UserId == UserId);
            if (userModel == null)
            {
                return Failed("用户信息错误！");
            }
            if (_siteMessage.UpdateIsRead(msgType.ToString(), userModel.UserId))
            {
                return Success("消息状态更新成功！");
            }
            else
            {
                return Failed("消息状态更新失败！");
            }
        }
        #endregion

        #region 用户未读消息条数
        /// <summary>
        /// 用户未读消息条数 lh
        /// </summary>
        /// <returns></returns>
        [HttpGet("messagecount")]
        public ApiResult MessageCount()
        {
            var userModel = _users.GetModel(c => c.UserId == UserId);
            if (userModel == null)
            {
                return Failed("用户信息错误！");
            }
            var count = _siteMessage.GetRecordCount(" ReceiverID=@0 AND ReceiverIsRead=@1 ", userModel.UserId, false);
            return DataResult(count);
        }
        #endregion

        #region 聊天列表
        /// <summary>
        /// 一对一聊天列表 lh
        /// </summary>
        /// <param name="otherUserID">聊天对象的ID</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("messagelistchat")]
        public ApiResult MessageListChat(int otherUserID, int pageIndex = 1, int pageSize = 10)
        {
            var userModel = _users.GetModel(c => c.UserId == UserId);
            if (userModel == null)
            {
                return Failed("用户信息错误");
            }
            var otherUserModel = _users.GetModel(c => c.UserId == otherUserID);
            if (otherUserModel == null)
            {
                return Failed("用户信息错误");
            }
            var list = _siteMessage.GetPagedList(pageIndex, pageSize,
                " (ReceiverID =@0 AND SenderID =@1) OR (SenderID =@0 AND ReceiverID =@1) ", " SendTime DESC ",
                userModel.UserId, otherUserModel.UserId);
            int count = _siteMessage.GetRecordCount(" (ReceiverID =@0 AND SenderID =@1) OR (SenderID =@0 AND ReceiverID =@1) ", userModel.UserId, otherUserModel.UserId);

            var listResult = new List<object>();

            //遍历消息的集合，给发送者和接收者的Ico图标赋值
            foreach (var item in list)
            {
                string senderIco = string.Empty;
                string receivIco = string.Empty;
                string content = string.Empty;
                //如果当前消息的发送者是userModel
                if (item.SenderID == userModel.UserId)
                {
                    //将发送者的图标设置为userModel的头像
                    if (!string.IsNullOrWhiteSpace(userModel.Gravatar))
                    {
                        senderIco = BaseConfig.ImagesDoMain + userModel.Gravatar;
                    }
                    else
                    {
                        //可以给senderIco加一个默认值
                    }
                    //将接收者的图标设置为otherUserModel的头像
                    if (!string.IsNullOrWhiteSpace(otherUserModel.Gravatar))
                    {
                        receivIco = BaseConfig.ImagesDoMain + otherUserModel.Gravatar;
                    }
                    else
                    {
                        //可以给senderIco加一个默认值
                    }
                }
                //如果当前遍历到的消息的发送者是otherUserModel
                else
                {
                    //将发送者的图标设置为otherUserModel的头像
                    if (!string.IsNullOrWhiteSpace(otherUserModel.Gravatar))
                    {
                        senderIco = BaseConfig.ImagesDoMain + otherUserModel.Gravatar;
                    }
                    else
                    {
                        //可以给senderIco加一个默认值
                    }
                    //将接收者的图标设置为userModel的头像
                    if (!string.IsNullOrWhiteSpace(userModel.Gravatar))
                    {
                        receivIco = BaseConfig.ImagesDoMain + userModel.Gravatar;
                    }
                    else
                    {
                        //可以给senderIco加一个默认值
                    }
                }

                //如果是聊天信息，且为图片，则加上图片服务器的路径
                if (item.MsgType == "chat" && (item.Ext1 == null ? false : item.Ext1.Contains("Pic")))
                {
                    content = BaseConfig.ImagesDoMain + item.Content;
                }
                else
                {
                    content = item.Content;
                }
                listResult.Add(new
                {
                    item.Id,
                    item.SenderID,
                    SenderIco = senderIco,
                    item.ReceiverID,
                    ReceiverIco = receivIco,
                    Content = content,
                    item.MsgType,
                    ContentType = item.Ext1,
                    SendTime = item.SendTime == null ? DateTime.Now.ToString("yyyy-MM-dd") : item.SendTime.ToString().ToDateTime().ToString("yyyy-MM-dd")
                });
            }
            return ListResult(listResult, count);
        }
        #endregion

        #region 发送消息 lh
        /// <summary>
        /// 发送消息 lh
        /// </summary>
        /// <param name="receiverId">接收者id</param>
        /// <param name="contentMsg">内容</param>
        /// <param name="contentType">内容类型</param>
        /// <returns></returns>
        [HttpGet("messagesend")]
        public ApiResult MessageSend(int receiverId, string contentMsg, string contentType)
        {
            var senderUser = _users.GetModel(c => c.UserId == UserId);
            var receiverUser = _users.GetModel(c => c.UserId == receiverId);
            if (senderUser == null || receiverUser == null)
            {
                return Failed("发送失败,用户信息错误");
            }
            if (string.IsNullOrWhiteSpace(contentMsg))
            {
                return Failed("信息不能为空");
            }
            if (contentType == "Service_Pic")
            {
                //如果为图片，需要进行的操作
            }
            //推送消息，并写入数据库

            Sykj.Entity.SiteMessage message = new Entity.SiteMessage()
            {
                SenderID = senderUser.UserId,
                ReceiverID = receiverUser.UserId,
                Title = "订单消息",
                MsgType = "Order",
                SendTime = DateTime.Now,
                Ext1 = contentType,
                SenderIsDel = false,
                ReaderIsDel = false,
                ReceiverIsRead = false,
                Content = contentMsg
            };
            _siteMessage.Add(message);

            return Success("发送成功");
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sendId"></param>
        /// <param name="contentMsg"></param>
        /// <param name="msgType"></param>
        /// <returns></returns>
        [HttpGet("sendmsgtest")]
        [AllowAnonymous]
        public ApiResult SendMsgTest(int sendId, string contentMsg, EnumHelper.MsgType msgType)
        {
            try
            {
                PushService pushService = Factory.CreatePushService();
                var list = new List<string> { "674" };
                pushService.Init(list, sendId, "消息测试", contentMsg, msgType,10);
                pushService.SendPush();
                return Success("发送成功");
            }
            catch (Exception ex)
            {
                return Failed(ex.Message);
            }


        }
    }
}